<?php
declare (strict_types=1);

namespace app\admin\middleware;

class Cors
{
    /**
     * 设置能访问的域名
     * @var string[]
     */
    static public $originarr = [
        '*', //允许所有域名
    ];

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取当前跨域域名
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        if (in_array('*', self::$originarr) || in_array($origin, self::$originarr)) {
            // 允许 $originarr 数组内的 域名跨域访问
            header('Access-Control-Allow-Origin:' . $origin);
            // 响应类型
            header('Access-Control-Allow-Methods:GET, POST, PUT,DELETE,OPTIONS,PATCH');
            // 带 cookie 的跨域访问
            header('Access-Control-Allow-Credentials: true');
            // 响应头设置
            header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type ,Keep-Alive, User-Agent, Accept, Access-Token, Token, Authorization, IgnoreCancelToken');
            if (request()->isOptions()) {
                exit();
            }
        }

        return $next($request);
    }
}
